﻿<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TrailGMap.ascx.cs" Inherits="Imageo.TrailGMap" %>
<%@ Register Assembly="FreeTextBox" Namespace="FreeTextBoxControls" TagPrefix="FTB" %>
<%-- 
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAmB4AqnPpTnZKO8aT7_HTtRQhe_Cu257Ef4avq-h53lMG9UAJahQhC1HK9QfBTkiOpeExLk_Q89-MNg" type="text/javascript"></script>
--%>
<%-- This key works for http://83.169.11.157:2080 
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAa9Y8f3ygWBLyti8f5n3TZBQmeMsi9Fqwj5gEggUBEe589Y1W3xQL0QHHoC6sgI2Y6rxYI6OB5ftgPQ" type="text/javascript"></script>
--%>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<div>
    <asp:HiddenField ID="hfProUserId" runat="server" />
    <asp:Panel ID="pnlMapControl" runat="server" Width="100%" Height="100%" Style="text-align: left; vertical-align: middle; font: 14px/14px Arial, Helvetica, sans-serif;">
        <table style="width: 100%; height: 100%;">
            <tr style="vertical-align: top;">
                <td>
                    <asp:Panel runat="server" ID="pnlTools" Style="text-align: left; display: none;">
                        <img id="imgToolMove" src="../images/Bsu.png" />
                        <img id="imgToolMoveSelected" src="../images/Bsd.png" />
                        <img id="imgToolAddWaypoint" src="../images/Bmu.png" />
                        <img id="imgToolAddWaypointSelected" src="../images/Bmd.png" />
                        <img id="imgToolDelWaypoint" src="../images/DelUp.png" />
                        <img id="imgToolDelWaypointSelected" src="../images/DelDo.png" />
                        <asp:ImageButton ID="btnSubmit" runat="server" ImageUrl="../images/save.png" OnClick="btnSubmit_Click" OnClientClick="saveJsonObjects();" />
                    </asp:Panel>
                </td>
                <td style="width: 100%; height: 100%;">
                    <div id="pnlMap" runat="server" style="height: 100%; width: 100%;" />
                </td>
                <td>
                    <asp:Panel ID="pnlMapSide" runat="server" Width="200" class="pnlCurvyWhite" Style="display: none;">
                        <div style="text-align: left;" class="normal_font">
                            <span style="font-weight: bold;">Waypoints:</span>
                            <div id="divMarkersortable" style="overflow: auto; height: 450px;">
                            </div>
                        </div>
                    </asp:Panel>
                </td>
            </tr>
        </table>
    </asp:Panel>
</div>
<div id="divTrailPopUp" style=" display: none; background: white; text-align:left; width: 400px;">
    <div style="clear: both">
        <a id="urlTrailName" style="clear: both" href="../ui/TrailDetails.aspx<%# Eval("OpenTrailUrl") %>" class="arial_heading_font_blue_16">
            <span id="txtTrailName" align="left">This is a name</span>
        </a>
    </div>
    <div style="clear: both">
        <div id="divImage" style="float: left; margin: 5px; width: 150px; height: 100px; background-color:Black; overflow:hidden; text-align: center; vertical-align: middle;">
            <img id="imgTrailPicture" alt="photo" src="../images/loading.gif" style="max-width: 150px; max-height: 100px;" />
        </div>
        <div id="divTrailDescr" style="vertical-align: top; margin: 5px; text-align: left; overflow:hidden; width: 180px; ">
            <div id="txtDescription">A round trip in South California that goes from San Diego to Los Angeles and the Anza Borrego Desert State Park through the Salton lake and the Joshua tree national Park </div>
        </div>
    </div>
</div>
<asp:HiddenField ID="hfJsonTrailData" runat="server" />
<asp:HiddenField ID="hfJsonMapData" runat="server" />

<script language="javascript" type="text/javascript">
    var jsonTrailData;
    var jsonMapData;

    var mapCanvas = document.getElementById('<%=pnlMap.ClientID %>');

    var arrMarker = new Array();                        // Array of markers
    var currTool = "move";                              // current tool
    var currWP = -1;                                    // current waypoint

    // Updates Toolbar buttons
    function UpdateMapToolbar() {
        if (!jsonMapData.canEdit) {
            // If we can't edit, hide toolbar
            currTool = "move";
            $("#<%=pnlTools.ClientID %>").hide();
            return;
        }

        // Otherwise, show the toolbar panel
        $("#<%=pnlTools.ClientID %>").show();
        if (currTool == "move") {
            $("#imgToolMove").hide();
            $("#imgToolMoveSelected").show();
            $("#imgToolAddWaypoint").show();
            $("#imgToolAddWaypointSelected").hide();
            $("#imgToolDelWaypoint").show();
            $("#imgToolDelWaypointSelected").hide();
        }

        if (currTool == "addWaypoint") {
            $("#imgToolMove").show();
            $("#imgToolMoveSelected").hide();
            $("#imgToolAddWaypoint").hide();
            $("#imgToolAddWaypointSelected").show();
            $("#imgToolDelWaypoint").show();
            $("#imgToolDelWaypointSelected").hide();
        }

        if (currTool == toolDelWaypoint) {
            $("#imgToolMove").show();
            $("#imgToolMoveSelected").hide();
            $("#imgToolAddWaypoint").show();
            $("#imgToolAddWaypointSelected").hide();
            $("#imgToolDelWaypoint").hide();
            $("#imgToolDelWaypointSelected").show();
        }
    }

    // Loads the data from the hidden field
    function LoadMapData() {
        /// Loads JSON data from the hidden field
        var hfJsonMapData = document.getElementById('<%=hfJsonMapData.ClientID %>');

        // parses json data and gets the objects
        if (hfJsonMapData && hfJsonMapData.value != "") {
            jsonMapData = JSON.parse(hfJsonMapData.value);
        }
        else {
            // if something fails, creates a default object
            jsonMapData = new Object();
            jsonMapData.canEdit = false;
            jsonMapData.centerLat = 0;
            jsonMapData.centerLon = 0;
            jsonMapData.zoomLevel = 0;
        }

        // Show this first, so gmap zooms correctly
        if (jsonMapData.canEdit) {
            $("#<%=pnlTools.ClientID %>").show();
            $("#<%=pnlMapSide.ClientID %>").show();
        }

        // Create WP Checkboxes on the side panel only if this is editable
        if (jsonMapData.canEdit) {
            UpdateWPSidePanel();
        } 
    }

    // Serializes everything back to the hidden field
    function saveJsonObjects() {
        if (jsonTrailData[0].waypointsField == undefined || jsonTrailData[0].waypointsField == null) {
            jsonTrailData[0].waypointsField = new Array();
        }
        // Storing the trail object in the hidden field
        $("#<%=hfJsonTrailData.ClientID %>").val(JSON.stringify(jsonTrailData));

        // Call this function only if someone has registered it
        if (functionSaveData != null) {
            functionSaveData();
        }
    }

    // Initializes the map
    function InitMap() {
        // center the map
        center = new google.maps.LatLng(jsonMapData.centerLat, jsonMapData.centerLon);

        // Force zoom level to an acceptable minimum
        zoomLevel = jsonMapData.zoomLevel;
        if (zoomLevel <= 0) zoomLevel = 2;

        var myOptions = {
            zoom: zoomLevel,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // Defines the map and the options
        document.map = new google.maps.Map(mapCanvas, myOptions);

        // Do we have an individual trail?
        if (jsonMapData.individualTrailMode) {
            if (jsonMapData.canEdit) {
                // If we can edit, adds the listeners
                google.maps.event.addListener(document.map, "click", function(event) {
                    if (currTool == "addWaypoint") {
                        AddNewWaypoint(event.latLng);        // On click draw location
                        currTool = "move";                // Unset add tool
                        currentWpIdx = arrMarker.length - 1;
                        currentWpImgIdx = 0;
                        UpdateWPSidePanel();
                        UpdateMarkerIcons();
                        UpdatePolyline();
                        UpdateMapToolbar();

                        if (functionUpdateWaypointInfo != null) {
                            currentWpImgIdx = 0;
                            functionUpdateWaypointInfo();
                        }
                        return;
                    }
                });
            }
        }
    }

    // Deletes the waypoint
    function deleteMarker(_wp) {
        var toDelete = -1;

        // Find the item we want to delete in the list
        for (var i = 0; i < arrMarker.length; i++) {
            if (_wp == arrMarker[i]) {
                toDelete = i;
            }
        }

        // If we found the item
        if (toDelete > 0) {
            var tmpTrail = jsonTrailData[0];
            var tmpOldWPs = new Array();

            // Copy the list to a temporary array
            for (var j = 0; j < jsonTrailData[0].waypointsField.length; j++) {
                tmpOldWPs.push(jsonTrailData[0].waypointsField[j]);
            }
            
            // Put them back excluding the item
            jsonTrailData[0].waypointsField = new Array();
            for (var j = 0; j < tmpOldWPs.length; j++) {
                if (toDelete != j)
                    jsonTrailData[0].waypointsField.push(tmpOldWPs[j]);
            }

            // Now update all controls
            ShowMarkers();
            UpdateMarkerIcons();
            UpdateWPSidePanel();
            UpdatePolyline();
        }
    }

    function ShowMarkers() {

        // Clear all markers
        if (arrMarker) {
            for (i in arrMarker) {
                arrMarker[i].setMap(null);
            }
        }

        // Create a new array of markers
        arrMarker = new Array();
        var tmpTrail = jsonTrailData[0];
        if (tmpTrail.waypointsField != null) {
            if (tmpTrail.waypointsField.length > 0) {
                var bounds = new google.maps.LatLngBounds;

                // draw markers
                for (var i = 0; i < tmpTrail.waypointsField.length; i++) {
                    var pos = new google.maps.LatLng(tmpTrail.waypointsField[i].waypointField.latitudeField, tmpTrail.waypointsField[i].waypointField.longitudeField);
                    bounds.extend(pos);                                 // update map bounds as we add markers
                    PlaceMarker(pos, tmpTrail.waypointsField[i]);       // place the waypoint
                }
                document.map.fitBounds(bounds);
            }
        }
    }

    function LoadTrailFromJson() {
        var hfJsonTrailData = document.getElementById('<%=hfJsonTrailData.ClientID %>');

        if (hfJsonTrailData && hfJsonTrailData.value != "") {
            jsonTrailData = JSON.parse(hfJsonTrailData.value);
        }
        else {
            jsonTrailData = new Array();
        }

        if (jsonMapData.individualTrailMode) {
            //// LOAD DATA
            ShowMarkers();
            UpdatePolyline();
        } else {
            //// LOAD DATA - FIRST MARKERS
            for (var i = 0; i < jsonTrailData.length; i++) {
                var pos = new google.maps.LatLng(jsonTrailData[i].latitudeField, jsonTrailData[i].longitudeField);
                // Set some default values
                if (jsonTrailData[i].titleField == "")
                    jsonTrailData[i].titleField = "Waypoint Name";
                // place the waypoint
                PlaceMarker(pos, jsonTrailData[i]);
            }
        }
        UpdateWPSidePanel();
        UpdateMarkerIcons();
    }

    var functionUpdateWaypointInfo;
    var functionUpdateWaypointOrder;
    var currPolyline = null;

    // Updates waypoint side panel
    function UpdateWPSidePanel() {
        $('#divMarkersortable').html('');       // Remove everything inside this div

        if (jsonTrailData == undefined || jsonTrailData == null) return;

        // Create nodes now
        if (jsonTrailData.length > 0) {
            var tmpTrail = jsonTrailData[0];
            try {
                if (tmpTrail.waypointsField != undefined || tmpTrail.waypointsField != null) {
                    for (var i = 0; i < tmpTrail.waypointsField.length; i++) {
                        var markerStr = "<div id='div%'><image id='img%'/><input id='txt%' type='text' class='flatTextBox' /></div>";
                        markerStr = markerStr.replace('%', i);
                        markerStr = markerStr.replace('%', i);
                        markerStr = markerStr.replace('%', i);
                        markerStr = markerStr.replace('%', i);

                        $("#divMarkersortable").append(markerStr);

                        $("#img" + i).attr('src', "../images/Marker/Trail" + (i + 1) + ".png");
                        $("#img" + i).attr('width', '18');
                        $("#img" + i).attr('height', '26');
                        $("#txt" + i).val(tmpTrail.waypointsField[i].waypointField.nameField);
                        $("#txt" + i).data('wpIdx', i);

                        $("#txt" + i).keyup(function() {
                            var itemId = $(this).data('wpIdx');
                            tmpTrail.waypointsField[itemId].waypointField.nameField = this.value;
                            if (functionUpdateWaypointInfo != null) {
                                // Must always update, so changes are shown
                                currentWpIdx = itemId;
                                currentWpImgIdx = 0;
                                functionUpdateWaypointInfo();
                            }
                        });

                        $("#txt" + i).click(function() {
                            var itemId = $(this).data('wpIdx');
                            if (functionUpdateWaypointInfo != null) {
                                if (currentWpIdx != itemId) {
                                    currentWpIdx = itemId;
                                    currentWpImgIdx = 0;
                                    functionUpdateWaypointInfo();
                                }
                            }
                        });
                    }
                }
            }
            catch (e) {
                debugger;
            }
        }
    }

    // if markername supplied no info window will b shown
    function PlaceMarker(pos, waypointObj) {
        // First, create waypoint in the map
        var image = new google.maps.MarkerImage("../images/Marker/Trail.png", null, null, null, new google.maps.Size(5, 5));
        var shadow = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
                                                    null,
                                                    new google.maps.Point(0, 0),
                                                    new google.maps.Point(0, 32));
        // Shapes define the clickable region of the icon.
        // The type defines an HTML <area> element 'poly' which
        // traces out a polygon as a series of X,Y points. The final
        // coordinate closes the poly by connecting to the first
        // coordinate.
        var shape = {
            coord: [1, 1, 1, 20, 18, 20, 18, 1],
            type: 'poly'
        };

        var newMarker = new google.maps.Marker({
            position: pos,
            map: document.map,
            icon: image,
            shadow: shadow,
            shape: shape,
            draggable: jsonMapData.canEdit
        });

        var tmpWP = jsonTrailData[0].waypointsField;
        var wpIdx = arrMarker.push(newMarker) - 1;
        newMarker.trailid = waypointObj

        if (jsonMapData.individualTrailMode) {
            /////////////////////////////////////////////////
            // ONLY ONE TRAIL !!!!
            /////////////////////////////////////////////////
            google.maps.event.addListener(newMarker, "click", function(pos, wp) {
                for (var i = 0; i < arrMarker.length; i++) {
                    if (newMarker == arrMarker[i]) {
                        if (currTool == "delWaypoint" && jsonMapData.canEdit) {
                            deleteMarker(newMarker);
                        } else {
                            if (functionUpdateWaypointInfo != null) {
                                if (currentWpIdx != i) {
                                    currentWpIdx = i;
                                    currentWpImgIdx = 0;
                                    functionUpdateWaypointInfo();
                                }
                            }
                        }
                    }
                }
            });

            if (jsonMapData.canEdit) {
                /////////////////////////////////////////////////
                // ONE TRAIL - CAN EDIT
                /////////////////////////////////////////////////
                google.maps.event.addListener(newMarker, "drag", function(pos, wp) {
                    var tmpTrail = jsonTrailData[0];
                    for (var i = 0; i < arrMarker.length; i++) {
                        if (newMarker == arrMarker[i]) {
                            // Update marker data and the polyline
                            tmpTrail.waypointsField[i].waypointField.longitudeField = newMarker.getPosition().lng();
                            tmpTrail.waypointsField[i].waypointField.latitudeField = newMarker.getPosition().lat();
                            UpdatePolyline();
                            if (functionUpdateWaypointInfo != null) {
                                if (currentWpIdx != i) {
                                    currentWpIdx = i;
                                    currentWpImgIdx = 0;
                                    functionUpdateWaypointInfo();
                                }
                            }
                        }
                    }
                });
            } else {
                /////////////////////////////////////////////////
                // ONE TRAIL - NO EDIT
                /////////////////////////////////////////////////
            }
        } else {
            /////////////////////////////////////////////////
            // MULTIPLE TRAILS
            /////////////////////////////////////////////////

            google.maps.event.addListener(newMarker, 'click', function() {
                showTrailPopUp(this.getPosition(), wpIdx);
            });
        }
    }

    function UpdateMarkerIcons() {
        for (var i = 0; i < arrMarker.length; i++) {
            var wpMarkerImage;

            if (i <= 30 && jsonMapData.individualTrailMode) {
                wpMarkerImage = new google.maps.MarkerImage("../images/Marker/Trail" + (i + 1) + ".png",
                                                                    null,
                                                                    null,
                                                                    new google.maps.Point(10, 32),
                                                                    new google.maps.Size(20, 32));
            } else {
                wpMarkerImage = new google.maps.MarkerImage("../images/Marker/Trail.png",
                                                                    null,
                                                                    null,
                                                                    new google.maps.Point(10, 32),
                                                                    new google.maps.Size(20, 32));
            }

            arrMarker[i].setIcon(wpMarkerImage);
            arrMarker[i].wpIdx = i;
        }
    }

    function UpdatePolyline() {
        try {
            if (currPolyline)
                currPolyline.setMap(null);

            if (jsonTrailData) {
                if (jsonTrailData.length > 0) {
                    try {
                        if (jsonTrailData[0].waypointsField == undefined || jsonTrailData[0].waypointsField == null) return;
                        if (jsonTrailData[0].waypointsField.length > 1) {

                            var pointArray = new Array();

                            for (var i = 0; i < jsonTrailData[0].waypointsField.length; i++) {
                                pointArray.push(new google.maps.LatLng(
                                jsonTrailData[0].waypointsField[i].waypointField.latitudeField,
                                jsonTrailData[0].waypointsField[i].waypointField.longitudeField
                            ));
                            }
                            currPolyline = new google.maps.Polyline({
                                path: pointArray,
                                strokeColor: "#FF0000",
                                strokeOpacity: 1.0,
                                strokeWeight: 2
                            });

                            currPolyline.setMap(document.map);
                        }
                    }
                    catch (e) {
                        debugger;
                    }
                }
            }
        }
        catch (e) {
            debugger;
        }
    }

    // Add a new waypoing to the trail
    function AddNewWaypoint(pos) {
        if (jsonTrailData.length > 0 && pos != undefined) {
            var tmpTrail = jsonTrailData[0];

            // Check the trail data
            if (tmpTrail.waypointsField == null) {
                tmpTrail.waypointsField = new Array();
            }

            // Create a new waypoint
            var waypoint = new Object();
            waypoint.imagesField = new Array();
            waypoint.orderNumberField = tmpTrail.waypointsField.length + 1;
            waypoint.scoreField = 0;

            // Create waypoint and set default values        
            waypoint.waypointField = new Object();
            waypoint.waypointField.nameField = "New waypoint";
            waypoint.waypointField.altitudeField = 0;
            waypoint.waypointField.cityField = "city";
            waypoint.waypointField.countryField = "country"
            waypoint.waypointField.createdField = 0;
            waypoint.waypointField.created1Field = 0;
            waypoint.waypointField.id1Field = 0;
            waypoint.waypointField.idField = 0;
            waypoint.waypointField.descriptionField = "Waypoint Description";
            waypoint.waypointField.provinceField = "";
            waypoint.waypointField.streetField = "";
            waypoint.waypointField.numberField = 0;
            waypoint.waypointField.zipcodeField = "";

            waypoint.waypointField.modified1Field = 1272376552330;
            waypoint.waypointField.modifiedField = 1272376552330;
            waypoint.waypointField.internalImageIdsField = "";
            waypoint.waypointField.userIdField = 0;
            waypoint.waypointField.numberaddendumField = null;
            waypoint.waypointField.repoPathField = "";

            waypoint.waypointField.annotationsField = new Array();
            waypoint.waypointField.imagesField = new Array();
            waypoint.waypointField.latitudeDoubleField = pos.lat();
            waypoint.waypointField.longitudeDoubleField = pos.lng();

            // Add the new waypoint to the trail
            tmpTrail.waypointsField.push(waypoint);

            // Place marker
            PlaceMarker(pos, waypoint);

            // Update location
            waypoint.waypointField.latitudeField = pos.lat();
            waypoint.waypointField.longitudeField = pos.lng();
        }
    }

    var _infoWindow;
    function showTrailPopUp(point, wpIdx) {
        // If we already have an info window, close it
        if (_infoWindow)
            _infoWindow.close();

        // If the point is inside bounds
        if (document.map.getBounds().contains(point)) {
            var wpObj = jsonTrailData[wpIdx];                   // This is only for multitrail... the structure is different

            var divTrailPopUpObj = $("#divTrailPopUp")[0];

            $("#imgTrailPicture").show();
            // Set picture properties
            if (wpObj.imageUrlField != "") {
                $("#imgTrailPicture").attr('src', ResolveUrl('/images/loading.gif'));
                if (wpObj.imageUrlField == null) {
                    $("#imgTrailPicture").attr('src', ResolveUrl('/images/photo_not_available.jpg'));
                } else {
                    $("#imgTrailPicture").attr('src', wpObj.imageUrlField.replace("type=image", "type=thumb"));
                }
            } else {
                $("#imgTrailPicture").attr('src', ResolveUrl('/images/photo_not_available.jpg'));
            }

            // Set Text Properties
            if (wpObj.titleField == "" || wpObj.titleField == null)
                $("#txtTrailName").html("No title");
            else          
                $("#txtTrailName").html(wpObj.titleField);

            var proUserId = $("#<%= hfProUserId.ClientID %>")[0].value;

            $("#urlTrailName").attr('href', "../ui/TrailDetails.aspx?trailid=" + wpObj.idField + proUserId);

            if (wpObj.descriptionField == "" || wpObj.descriptionField == null)
                $("#txtDescription").html("No description");
            else
                $("#txtDescription").html(wpObj.descriptionField);

            ///////////////////////////
            // Close commands

            var wp = arrMarker[wpIdx];

            //            google.maps.event.addListener(wp, "mouseover", function() {
            //                try { clearTimeout(wp.timeout); }
            //                catch (e) { }
            //            });

            //            google.maps.event.addListener(wp, "mouseout", function() {
            //                var tmp = setTimeout(function() {
            //                    _infoWindow.close();
            //                }, 2000);
            //                wp.timeout = tmp;
            //            });

            _infoWindow = new google.maps.InfoWindow({
                content: $("#divTrailPopUp").html()
            });
            _infoWindow.open(document.map, wp);
        }
    }

    // Define an special sorting order for waypoints
    function sortfunctionWP(a, b) {
        try {
            return a.orderNumberField - b.orderNumberField;
        }
        catch (e) {
        }
        return 0;
    }

    // Set toolbar actions
    function setupToolbar() {
        $("#imgToolMove").click(function() {
            currTool = "move";
            UpdateMapToolbar();
        });

        $("#imgToolAddWaypoint").click(function() {
            if (jsonMapData.easyMode) {
                if (jsonTrailData[0].waypointsField != null) {
                    if (jsonTrailData[0].waypointsField.length > 0) {
                        alert("You are in easy mode, you can only set one waypoint");
                        return;
                    }
                }
            }
            currTool = toolAddWaypoint;
            UpdateMapToolbar();
        });

        $("#imgToolDelWaypoint").click(function() {
            currTool = "delWaypoint";
            UpdateMapToolbar();
        });

        UpdateMapToolbar();
    }


    /////////////////////////////////////////////
    /// MAIN JAVASCRIPT CODE - READY FUNCTION
    ////////////////////////////////////////////
    $(document).ready(function() {
        LoadMapData();
        setupToolbar();
        InitMap();
        LoadTrailFromJson();

        // Prepare sortable marker list
        $("#divMarkersortable").sortable(
	    {
	        update: function(event, ui) {
	            if (!jsonMapData.canEdit) return;
	            if (jsonTrailData.length <= 0) return;

	            var newOrder = $(this).sortable('toArray');
	            var arrNewOrder = new Array();
	            // First create a vector with the new order
	            for (var i = 0; i < newOrder.length; i++) {
	                arrNewOrder.push(parseInt(newOrder[i].replace('div', '')));
	            }

	            var tmpTrail = jsonTrailData[0];
	            var tmpOldWPs = new Array();

	            for (var i = 0; i < jsonTrailData[0].waypointsField.length; i++) {
	                tmpOldWPs.push(jsonTrailData[0].waypointsField[i]);
	            }

	            jsonTrailData[0].waypointsField = new Array();
	            for (var i = 0; i < arrNewOrder.length; i++) {
	                var wp = tmpOldWPs[arrNewOrder[i]];
	                wp.orderNumberField = i + 1;
	                jsonTrailData[0].waypointsField.push(wp);
	            }

	            //	            // Sort here
	            //	            jsonTrailData[0].waypointsField.sort(sortfunctionWP);

	            // Now update all controls
	            ShowMarkers();
	            UpdateMarkerIcons();
	            UpdateWPSidePanel();
	            UpdatePolyline();

	            currentWpIdx = -1;
	            if (functionUpdateWaypointOrder != null) {
	                functionUpdateWaypointOrder();
	            }
	        }
	    });
        $("#divMarkersortable").disableSelection();

    });
    
</script>

